﻿@namespace Project.Web.Shared.Components
@*
    自定义 UI 中的连接状态 (Blazor Server)
    https://learn.microsoft.com/zh-cn/aspnet/core/blazor/fundamentals/signalr?view=aspnetcore-7.0#reflect-the-connection-state-in-the-ui-blazor-server
*@
<div id="components-reconnect-modal">
    <div class="reconnect-state show">
        @if (ReconnectingTemplate != null)
        {
            @ReconnectingTemplate
        }
        else
        {
            <div class="message">
                There was a problem with the connection!
                (Current reconnect attempt:
                <span id="components-reconnect-current-attempt"></span> /
                <span id="components-reconnect-max-retries"></span>)
            </div>
        }
    </div>

    <div class="reconnect-state failed">
        @if (ReconnectFailedTemplate != null)
        {
            @ReconnectFailedTemplate
        }
        else
        {
            <div class="message">Oh snap! Failed to reconnect with the server. This is typically caused by a longer network outage, or if the server has been taken down. You can try to <a href="javascript:window.Blazor.reconnect()">reconnect</a>, but if that does not work, you need to <a href="javascript:location.reload()">reload</a> the page.</div>
        }
    </div>

    <div class="reconnect-state rejected">
        @if (ReconnectRejectedTemplate != null)
        {
            @ReconnectRejectedTemplate
        }
        else
        {
            <div class="message">Oh man! The server rejected the attempt to reconnect. The only option now is to <a href="javascript:location.reload()">reload</a> the page, but be prepared that it won't work, since this is typically caused by a failure on the server.</div>
        }
    </div>
</div>
@code {
    [Parameter]
    public bool AutoReconnect { get; set; } = true;
    /// <summary>
    /// 正在重连的模板
    /// </summary>
    [Parameter]
    public RenderFragment? ReconnectingTemplate { get; set; }

    /// <summary>
    /// 重连失败的模板
    /// </summary>
    [Parameter]
    public RenderFragment? ReconnectFailedTemplate { get; set; }

    /// <summary>
    /// 服务器拒绝的模板
    /// </summary>
    [Parameter]
    public RenderFragment? ReconnectRejectedTemplate { get; set; }

    [Inject, NotNull] public IReconnectorProvider? Provider { get; set; }

    public override Task SetParametersAsync(ParameterView parameters)
    {
        Provider.RegisterView(ApplyTemplate);
        return base.SetParametersAsync(parameters);
    }

    private void ApplyTemplate(IReconnector reconnector)
    {
        this.ReconnectingTemplate = reconnector.ReconnectingTemplate;
        this.ReconnectFailedTemplate = reconnector.ReconnectFailedTemplate;
        this.ReconnectRejectedTemplate = reconnector.ReconnectRejectedTemplate;
        StateHasChanged();
    }

}
